#pragma once
#include "Socket.hpp"
#include <iostream>
#include <memory>
#include<poll.h>

class SelectServer
{
    const static int gnum = sizeof(fd_set) * 8;
    const static int gdefaultfd = -1;

private:
    
    void Accepter()
    {
        InetAddr addr;
        int sockfd = _listensock->Accepter(&addr);
        // 添加到监视rfds集
        for (int i = 0; i < gnum; i++)
        {
            if (fd_events[i].fd == gdefaultfd)
            {
                fd_events[i].fd = sockfd;
                fd_events[i].events = POLLIN;
                LOG(INFO, "add %d to fd_array success!\n", sockfd);
                break;
            }
        }
    }
    void HandlerIO(int i)
    {
        // 直接开读，一定不会阻塞
        char buffer[1024];
        ssize_t n = read(fd_events[i].fd, buffer, sizeof(buffer)-1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;
            std::string content = "<html><body><h1>hello bite</h1></body></html>";
            std::string echo_str = "HTTP/1.0 200 OK\r\n";
            echo_str += "Content-Type: text/html\r\n";
            echo_str += "Content-Length: " + std::to_string(content.size()) + "\r\n\r\n";
            echo_str += content;
            // echo_str += buffer;
            ::send(fd_events[i].fd, echo_str.c_str(), echo_str.size(), 0); // 临时方案
        }
        else if (n == 0)
        {
            LOG(INFO, "client quit...\n");
            // 关闭fd
            ::close(fd_events[i].fd);
            // select 不要在关心这个fd了
            fd_events[i].fd = gdefaultfd;
        }
        else
        {
            LOG(ERROR, "recv error\n");
            // 关闭fd
            ::close(fd_events[i].fd);
            // select 不要在关心这个fd了
            fd_events[i].fd = gdefaultfd;
        }
    }
    void HandlerEvent()
    {
        for (int i = 0; i < gnum; i++)
        {
            if (fd_events[i].fd == gdefaultfd)
                continue;
            if (fd_events[i].revents & POLLIN) // 就绪且合法
            {
                if (fd_events[i].fd == _listensock->Sockfd())
                    Accepter();
                else
                    HandlerIO(i);
            }
        }
    }

public:
    SelectServer(uint16_t port)
        : _port(port), _listensock(std::make_unique<tcp_Socket>())
    {
        _listensock->BuildListenSocket(_port);
    }
    void Init()
    {
        //初始化
        //所有监视设为默认fd
        for (int i = 0;i < gnum;i++)
        {
            fd_events[i].fd = gdefaultfd;
            fd_events[i].events = 0;
            fd_events[i].revents = 0;
        }
        fd_events[0].fd = _listensock->Sockfd();
        fd_events[0].events = POLLIN;
    }
    void Loop()
    {
        while (true)
        {
            int timeout = 3000;

            // 进行多路转接
            int n = poll(fd_events, gnum, timeout);
            if (n > 0)
            {
                LOG(INFO, "have event ready,n: %d\n", n);
                HandlerEvent();
                PrintDebug();
            }
            else if (n == 0)
            {
                LOG(DEBUG, "time out\n");
                continue;
            }
            else if (n == -1)
            {
                LOG(ERROR, "select error\n");
                break;
            }
        }
    }
    void PrintDebug()
    {
        std::cout << "fd list: ";
        for (int i = 0; i < gnum; i++)
        {
            if (fd_events[i].fd == gdefaultfd)
                continue;
            std::cout << fd_events[i].fd<< " ";
        }
        std::cout << "\n";
    }
    ~SelectServer() 
    {
        
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
    struct pollfd fd_events[gnum];//辅助数组//作为输入和输出
};